//
//  RCOAuthViewController.swift
//  RCWeibo
//
//  Created by CL on 15/12/15.
//  Copyright © 2015年 CL. All rights reserved.
//

import UIKit
import SVProgressHUD
import AFNetworking

class RCOAuthViewController: UIViewController, UIWebViewDelegate {
    
    
    let webView = UIWebView()
    override func loadView() {
        //替换默认view为webview
        view = webView
        
        webView.delegate = self
        
        
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        //添加nav的关闭按钮
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: .Plain, target: self, action: "close")
        //添加自动填充按钮
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", style: .Plain, target: self, action: "defaultAccount")
        
        //加载oauth授权页面
        loadOAuthPage()
        
    }
    //MARK:
    //MARK:nav item 按钮点击事件
    //关闭webview
    @objc  private  func close(){
        //回到主界面
        SVProgressHUD.dismiss()
        dismissViewControllerAnimated(true) { () -> Void in
            
            print("我回去了")
            
        }
    }
    // 自动填充
    @objc private func defaultAccount(){
        
        // 调用js代码
        let jsStr = "document.getElementById('userId').value = '350926510@qq.com', document.getElementById('passwd').value = 'CDMA123456+' "
        webView.stringByEvaluatingJavaScriptFromString(jsStr)
        
    }
    
    //加载oauth授权页面
    func loadOAuthPage(){
        
        let urlStr = "https://api.weibo.com/oauth2/authorize?" + "client_id=" + client_id + "&redirect_uri=" + redirect_uri
        
        if let url = NSURL(string: urlStr) {
            //请求授权网页
            webView.loadRequest(NSURLRequest(URL: url))
            
        }
        
    }
    
    
}

// MARK: - 为webview添加等待动画
extension RCOAuthViewController{
    
    func webViewDidStartLoad(webView: UIWebView) {
        
        SVProgressHUD.show()
    }
    
    func webViewDidFinishLoad(webView: UIWebView) {
        
        SVProgressHUD.dismiss()
    }
    
    //MARK:
    //MARK:过滤无效的url
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        //
        let urlStr = request.URL?.absoluteString ?? "~~~~~~"
        
        if urlStr.hasPrefix("https://api.weibo.com"){
            
            return true
        }
        
        if !urlStr.hasPrefix("http://www.baidu.com/?code="){
            
            return false
        }
        
        print(urlStr)
        
        //到这里的就是code了，截取code
        guard let query = request.URL?.query else{
            
            //如果获取不到query
            return false
            
        }
        //code=6fc9986be1c6a612ee8aef191f6968ab
        //获取code码
        let code = query.substringFromIndex("code=".endIndex)
        
        
        //通过code获取用户token
        RCUserAccountViewModel().laodAccessToken(code) { (isSuccess) -> () in
            
            if isSuccess{
            
                print("登录成功")
                SVProgressHUD.dismiss()
            //先dismiss再切控制器
                self.dismissViewControllerAnimated(false, completion: { () -> Void in
                    
                    defaultNotification.postNotificationName(WBSwitchRootVCNote, object: nil)
                })
                
            }else{
            
                print("登录失败")
            }
        }
        
//        return true
                return false
    }
    
       
    
}
